package com.iocaop.uaa.security.filter;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RequiredArgsConstructor
public class RestAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    // 序列化需要使用的对象
    private final ObjectMapper objectMapper;


    /**
     * 重写认证方法
     *
     * {
     *     "username":"123456",
     *     "password":"123456"
     * }
     * @param request
     * @param response
     * @return
     * @throws AuthenticationException
     */
    @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException {
        UsernamePasswordAuthenticationToken authRequest = null;
        // 获取请求中的参数
        try {
            // 读请求流
            ServletInputStream is = request.getInputStream();
            // 转成json
            JsonNode jsonNode = objectMapper.readTree(is);
            String username = jsonNode.get("username").textValue();
            String password = jsonNode.get("password").textValue();
            if (null==username){
                username="";
            }
            if (null==password){
                password="";
            }
            // 构建安全对象
            authRequest = new UsernamePasswordAuthenticationToken(
                username, password);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BadCredentialsException("没有找到用户名和密码");
        }
        // 模仿父类 返回  ---后续在学习细节 这里只是copy
        return this.getAuthenticationManager().authenticate(authRequest);
    }
}
